import requests
import json

cookie = {}
with open("config.json") as fs:
    cookie = json.load(fs)


def query(begin, end):
    global cookie
    url = "http://crm.jpushoa.com/api/web/clue/developerList/findByPage?page=1&pageSize=100&queryType=companyName&keyword=公司&sTime=%s&eTime=%s" % (
        begin, end)
    res = requests.get(url, cookies=cookie)
    return res.json()


def sum(data):
    ret = []
    for it in data["data"]["list"]:
        cpName = it["companyName"]
        if it["province"] in ["上海市", "浙江省", "安徽省", "江苏省"]:
            ret.append(cpName)

    return ret

def getCompanySaler(name):
    res = requests.get(
        "https://crm.jpushoa.com/api/web/customer/company/getCompanyList?page=1&pageSize=10&keyword=%s"
        % name,
        cookies=cookie,
    )

    jsonData = res.json()

    if len(jsonData["data"]["list"])<=0:
        return "未找到"

    return jsonData["data"]["list"][0]["customers"][0]["saleIdName"]

def printAndWrite(file,str):
    file.write(str)
    print(str)

if __name__ == "__main__":
    # fs = open("./query.json")
    # text = fs.read()
    # data = json.loads(text)
    # data = sum(data)

    begin = cookie["begin"]
    end = cookie["end"]
    data = sum(query(begin, end))

    fs = open("./result/%s-%s.txt" % (begin, end), "w")
    cnt = len(data)

    nameArr={}
    printAndWrite(fs,"company:\n")
    for it in data:
        saler = getCompanySaler(it)
        nameArr[saler] = nameArr.get(saler,0)+1
        line = "%s\t%s\n" % (saler,it)
        printAndWrite(fs,line)

    printAndWrite(fs,"total:%s\n\n" % cnt)

    printAndWrite(fs,"saler:\n")
    for name,cnt in nameArr.items():
        printAndWrite(fs, "%s -> %s" % (name,cnt))

    fs.close()
